<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keywords" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表   :data="departments"绑定模型层数据-->
		<el-table :data="systemdictionaryDetail" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="200">
			</el-table-column>
			<el-table-column type="index" label="编号" width="300">
			</el-table-column>
      <el-table-column prop="name" label="明细名" width="320" sortable>
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
		</el-table>
		<!--工具条 批量删除和分页条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		<!--新增界面-->
    <!--
        :visible.sync 控制窗体是否显示
        :rules=" 绑定表单的校验规则
         prop=" 绑定模型层的属性校验规则
         ref="addForm"  给当前表单去一个引用的别名
		-->
		<el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="明细名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典名称" prop="type_id">
          <el-select v-model="addForm.types_id" clearable value-key="id" placeholder="请选择">
            <el-option
                v-for="item in systemdictionaryType"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              <span style="float: left;">{{ item.name }}</span>
            </el-option>
          </el-select>
          <!--          <el-input v-model="addForm.manager" auto-complete="off"></el-input>-->
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {

				filters: {
          keywords: ''
				},
        title:null,
        systemdictionaryType: [],
        systemdictionaryDetail:[],
        deptTree:[],
				total: 0,
				currentPage: 1,
        pageSize:8,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},

				addFormVisible: false,//新增界面是否显示
        detailFormVisible:false, //查看详情界面是否显示
				addLoading: false,
        //校验规则
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          name:'',
          types_id:''
				}
			}
		},
		methods: {
			//性别显示转换
			/*formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},*/
			handleCurrentChange(val) {
				this.currentPage = val;
        this.getDictionaryTypes();
			},
      //高级查询按钮
      search(){
        // 定位到第一页
        this.currentPage = 1;
        //调用查询刷新页面
        this.getDictionaryTypes();
      },
			//获取数据字典列表
      getDictionaryTypes() {
				let para = {
					currentPage: this.currentPage,
          pageSize: this.pageSize,
          keywords: this.filters.keywords//关键字查询
				};
				this.listLoading = true;  //开启忙等
				console.log("woshiadj"+para)
				this.$http.post("/DicDetail",para)  //把获取到的模型层数据传给后端接口
            .then(result=>{  //如果对接成功，返回后台数据
              this.listLoading = false;//关闭忙等框
              console.log(result);
              this.getTypes();
              result = result.data;
              this.systemdictionaryType = result.dataAll;   //查询返回的所有数据---我的后端字段用的dataAll
              this.total = result.total;  //返回数据的总条数，用于分页
            })
            .catch(result=>{   //如果没有拿到数据，或出现系统问题给出用户提示信息
              this.$message.error('网络出现问题，请稍后再试！！');
            })
			},
      getTypes(){
        this.$http.get("/DicType")  //把获取到的模型层数据传给后端接口
            .then(result=>{  //如果对接成功，返回后台数据
              this.listLoading = false;//关闭忙等框
              console.log(result);
              this.systemdictionaryType = result.data;//相当于PageList
            })
            .catch(result=>{   //如果没有拿到数据，或出现系统问题给出用户提示信息
              this.$message.error('网络出现问题，请稍后再试！！');
            })
      },
      //获取详情信息
      getDetails(){
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keywords: this.filters.keywords//关键字查询
        };
        this.listLoading = true;  //开启忙等
        this.$http.post("/DicDetail",para)  //把获取到的模型层数据传给后端接口
            .then(result=>{  //如果对接成功，返回后台数据
              this.listLoading = false;//关闭忙等框
              result = result.data;//相当于PageList
              this.systemdictionaryDetail = result.dataAll;   //查询返回的所有数据---我的后端字段用的dataAll
              this.total = result.total;   //返回数据的总条数，用于分页
            })
            .catch(result=>{   //如果没有拿到数据，或出现系统问题给出用户提示信息
              this.$message.error('网络出现问题，请稍后再试！！');
            })
      },
			//单条删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = false;
					//NProgress.start();
					let id = row.id;   //获取到当前要删除对象的id值
					this.$http.delete("/DicDetail/"+id)  //发送请求到后端，把id传过去
              .then(result=>{
                 console.log("删除返回的结果："+result);
                 let res = result.data;
                 if (res.success){
                   this.$message({
                     message: '删除成功!',
                     type: 'success'
                   });
                 }else {
                   this.$message.error('操作失败！！');
                 }
                 this.currentPage = 1;
                 this.getDetails();
              })
              .catch(result=>{
                console.log(result);
              })
				}).catch(() => {
          this.$message('已取消删除');
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  this.getDeptTree();
			  this.title = "编辑";
				this.addFormVisible = true;
				this.addForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
			  this.getDeptTree();
			  this.title = "新增";
				this.addFormVisible = true;
				this.addForm = {
          name:''
				};
			},
			//新增和编辑
			addSubmit: function () {
			  //开启校验
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);  //克隆数据赋值给变量para
              console.log(para);
							//para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
              if(para.parent){//如果parent有值
                //将数组格式转换成对象
                para.parent = {"id":para.parent[para.parent.length-1]}
              }
							this.$http.put("/DicDetail",para)
                .then(res => {
                  this.$refs['addForm'].resetFields();//重置表单校验
								  this.addLoading = false;  //关闭按钮忙等
                  this.addFormVisible = false;  //关闭弹出框
								//NProgress.done();
                  res = res.data;
                  if (res.success){
                    this.$message({
                      message: '提交成功',
                      type: 'success'
                    });
                  }else {
                    this.$message({
                      message: res.message,
                      type: 'error'
                    });
                  }
                  this.$refs['addForm'].resetFields();
                  this.addLoading = false;  //关闭按钮忙等
                  this.addFormVisible = false;  //关闭弹出框
                  this.getDetails();
							})
            .catch(res=>{   //如果没有拿到数据，或出现系统问题给出用户提示信息
               this.addLoading = false;  //关闭按钮忙等
               this.addFormVisible = false;  //关闭弹出框
               this.$message.error('网络出现问题，请稍后再试！！');
               this.getDetails();
              })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				//var ids = this.sels.map(item => item.id).toString();
				var ids = this.sels.map(item => item.id);   //遍历获取到每个对象的id值 并把这些id封装到map集合中赋值给ids变量
				console.log(ids);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;  //开启忙等框
					//NProgress.start();
					//let para = { ids: ids };
					this.$http.patch("/DicDetail",ids)  //进行批量操作时，用patch来发送请求
          .then(result=>{   //操作执行成功时返回的结果
              console.log("删除返回的结果："+result);
              let res = result.data;
              if (res.success){
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else {
                this.$message.error('操作失败！！');
              }
              this.currentPage = 1;
              this.getDetails();
            })
            .catch(result => {
              console.log("删除返回的错误信息："+result);
            })
				}).catch(() => {
          this.$message('已取消删除');
				});
			},

      getDeptTree(){
        this.$http.get("/DicDetail/tree").then(result=>{
          this.deptTree = result.data;
        })
      }
    },
		mounted() {
      this.getDictionaryTypes();
      this.getDetails();
      this.getTypes();
		}
	}

</script>

<style scoped>

</style>